//
//  GoodsAddressDetailViewController.m
//  1gene
//
//  Created by 1jiyin on 16/5/6.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "GoodsAddressDetailViewController.h"
#import "ProvinceSelectedViewController.h"

@interface GoodsAddressDetailViewController ()

@property(nonatomic,copy)UITextField *city1;

@property(nonatomic,copy)UITextField *detail1;

@property(nonatomic,copy)UITextField *receiver1;

@property(nonatomic,copy)UITextField *phone1;


@property(nonatomic,copy)NSString *province;
@property(nonatomic,copy)NSString *city;

@property(nonatomic,assign)BOOL addressChanged;

@end

@implementation GoodsAddressDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:[UIView new]];
    _addressChanged=NO;
    [self createNavigation];
    [self createUI];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNotification:) name:@"myChangeCity" object:nil];
    // Do any additional setup after loading the view.
}
-(void)getNotification:(NSNotification *)notify
{
    NSDictionary *dic=notify.userInfo;
    UITextField *text=(id)[self.view viewWithTag:1];
    text.text=[NSString stringWithFormat:@"%@%@%@",dic[@"province"],dic[@"city"],dic[@"qu"]];
    _province=dic[@"province"];
    _city=[NSString stringWithFormat:@"%@%@",dic[@"city"],dic[@"qu"]];
}
-(void)createUI
{
    NSArray *arr;
    if (_modelState==1) {
         arr=@[@"",@"",@"",@""];
    }else{
        arr=@[[NSString stringWithFormat:@"%@%@",_model.province,_model.city],_model.detail,_model.receiver,_model.phone];
    }
    NSArray *arr2=@[@"地区",@"详细地址",@"收货人姓名",@"手机号码"];
    for (int i=0; i<arr.count; i++) {
        UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(10, 10+(30+10)*i, self.view.frame.size.width-110, 50)];
        text.text=arr[i];
        text.tag=i+1;
        text.font=[UIFont systemFontOfSize:16];
        text.textColor=[UIColor blackColor];
        text.clearButtonMode=UITextFieldViewModeAlways;
        
        [self.view addSubview:text];
        
        if (i<1) {
            text.placeholder=@"请选择";
            text.clearButtonMode= UITextFieldViewModeNever;
            UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(text.frame)+10, text.frame.origin.y, 60, 50)];
            lab.text=arr2[i];
            lab.font=[UIFont systemFontOfSize:12];
            lab.textColor=[UIColor grayColor];
            lab.textAlignment=NSTextAlignmentRight;
            [self.view addSubview:lab];
            
            UIButton *changeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            changeBtn.frame=CGRectMake(CGRectGetMaxX(lab.frame)+5, lab.frame.origin.y+(50-20)/2.0, 20, 20);
            [changeBtn setBackgroundImage:[UIImage imageNamed:@"app_right"] forState:UIControlStateNormal];
            [self.view addSubview:changeBtn];
            
            
            UIButton *changeBtn1=[UIButton buttonWithType:UIButtonTypeCustom];
            changeBtn1.frame=CGRectMake(lab.frame.origin.x, lab.frame.origin.y, CGRectGetMaxX(changeBtn.frame)-lab.frame.origin.x, lab.frame.size.height);
            [changeBtn1 addTarget:self action:@selector(changeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            changeBtn1.tag=100+i;
            [self.view addSubview:changeBtn1];
            text.userInteractionEnabled=NO;
        }else{
            text.placeholder=@"请填写";
            text.clearButtonMode= UITextFieldViewModeAlways;
            UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(text.frame)+10, text.frame.origin.y, 90, 50)];
            lab.text=arr2[i];
            lab.font=[UIFont systemFontOfSize:12];
            lab.textColor=[UIColor grayColor];
            lab.textAlignment=NSTextAlignmentCenter;
            [self.view addSubview:lab];

        }
        
        if(i==0){
            _city1=text;
        }else if (i==1){
            _detail1=text;
        }else if (i==2){
            _receiver1=text;
        }else if (i==3){
            _phone1=text;
        }
    }
}

-(void)changeBtnClick:(UIButton *)sender
{
    if (sender.tag==100) {
        _addressChanged=YES;
        ProvinceSelectedViewController *vc=[ProvinceSelectedViewController new];
        vc.myState=1;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)createNavigation
{
    self.navigationController.navigationBar.hidden=NO;
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(0, 0, 25, 25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.bounds=CGRectMake(0, 0, 50, 25);
    rightBtn.layer.borderColor=[UIColor whiteColor].CGColor;
    rightBtn.layer.borderWidth=1.0;
    rightBtn.layer.cornerRadius=5.0;
    rightBtn.backgroundColor=[UIColor whiteColor];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitleColor:[UIColor colorWithRed:243/255.0 green:132/255.0 blue:0 alpha:1] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
}

#pragma mark 返回上一页
-(void)leftBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 保存
-(void)rightBtnClick:(UIButton *)sender
{
    [self.navigationController.view endEditing:YES];
    if (_city1.text.length==0) {
        [self.view showTiShiMessage:@"地区不能为空"];
        return;
    }
    if (_detail1.text.length==0) {
        [self.view showTiShiMessage:@"详细地址不能为空"];
        return;
    }
    
    if (_receiver1.text.length==0) {
        [self.view showTiShiMessage:@"姓名不能为空"];
        return;
    }
    
    if (_phone1.text.length==0) {
        [self.view showTiShiMessage:@"手机号码不能为空"];
        return;
    }
    
    if (![self checkTel:_phone1.text]) {
        return;
    }
    
    if (_modelState==1) {
        //添加
        [self addAddress];
    }else{
        //修改
        [self changeAddress];
    }
}

#pragma mark 判断手机号码的正则表达式
- (BOOL)checkTel:(NSString *)str

{
    
    if ([str length] == 0) {
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码不能为空" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return NO;
        
    }
    
    //1[0-9]{10}
    
    //^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
    
    //    NSString *regex = @"[0-9]{11}";
    
    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:str];
    
    if (!isMatch) {
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式不正确" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
        return NO;
        
    }
    
    
    
    return YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController.navigationBar setTranslucent:NO];
}

//添加收货地址
-(void)addAddress
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    NSDictionary *params=@{@"province":_province,@"city":_city,@"receiver":_receiver1.text,@"phone":_phone1.text,@"detail":_detail1.text,@"is_default":@"0"};
    
    [self.view showCicle:YES];
    
    [manager POST:[NSString stringWithFormat:AddAddress,token] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
         [self.view showCicle:NO];
        [self.view showTiShiMessage:@"添加成功"];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"添加收货地址%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self.view showCicle:NO];
        [self.view showTiShiMessage:@"添加失败"];
        NSLog(@"error%@",error.localizedDescription);
    }];
}

//修改收货地址
-(void)changeAddress
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    NSDictionary *params;
    if (_addressChanged) {
        params=@{@"province":_province,@"city":_city,@"receiver":_receiver1.text,@"phone":_phone1.text,@"detail":_detail1.text,@"is_default":@"0"};
    }else{
        params=@{@"province":_model.province,@"city":_model.city,@"receiver":_receiver1.text,@"phone":_phone1.text,@"detail":_detail1.text,@"is_default":@"0",@"address_id":_model.addressId};
    }
    
     [self.view showCicle:YES];
    
    [manager POST:[NSString stringWithFormat:ChangeAddress,token] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
         [self.view showCicle:NO];
        [self.view showTiShiMessage:@"修改成功"];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"修改收货地址%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self.view showCicle:NO];
        [self.view showTiShiMessage:@"修改失败"];
        NSLog(@"error%@",error.localizedDescription);
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
     [self.navigationController.view endEditing:YES];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [self.navigationController.navigationBar setTranslucent:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
